import React, { createContext, useReducer, useState, useEffect } from "react";
import { Alert } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import query from "../../api/query";

const TestContext = createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "fetch_init":
      return action.payload;
    case "add_test":
      return [...state, action.payload];
    case "edit_test": //传入试卷对象
      return state.map((item) => {
        return item._id === action.payload._id ? action.payload : item;
      });
    case "delete_test": //传入试卷_id
      return state.filter((item) => item._id !== action.payload);
    case "set_status":
      return action.payload;
  }
};

export const TestProvider = ({ children }) => {
  const [testLists, dispatch] = useReducer(dataReducer, []);
  const [isTestLoading, setIsTestLoading] = useState(false);
  const [isTestError, setIsTestError] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsTestLoading(true);
      setIsTestError(false);

      try {
        const token = await AsyncStorage.getItem("token");
        const result = await query.get("/test", {
          headers: { Authorization: token },
        });
        dispatch({ type: "fetch_init", payload: result.data.data });
      } catch (err) {
        setIsTestError(true);

        console.log("初始化试题出错", err);
      }
      setIsTestLoading(false);
    };
    fetchData();
  }, []);

  const addTest = async (test, callback) => {
    try {
      setIsTestLoading(true);
      const token = await AsyncStorage.getItem("token");
      const result = await query.post("/test", test, {
        headers: { Authorization: token },
      });
      dispatch({ type: "add_test", payload: result.data.data });
      Alert.alert("", "添加试卷成功", [
        {
          text: "确定",
          onPress: () => callback(),
        },
      ]);
    } catch (err) {
      console.log("添加试卷失败", err);
      Alert.alert("", "添加试卷失败");
    }
    setIsTestLoading(false);
  };

  const editTest = async (test, callback) => {
    try {
      setIsTestLoading(true);
      const token = await AsyncStorage.getItem("token");
      const result = await query.patch("/test/" + test._id, test, {
        headers: { Authorization: token },
      });
      dispatch({ type: "edit_test", payload: result.data.data });
      Alert.alert("", "试卷修改成功", [
        {
          text: "确定",
          onPress: () => callback(),
        },
      ]);
    } catch (err) {
      console.log("修改试卷失败", err);
      Alert.alert("", "修改试卷失败");
    }
    setIsTestLoading(false);
  };

  //不开放该功能 仅做测试用
  const deleteTest = async (testId) => {
    try {
      setIsTestLoading(true);
      const token = await AsyncStorage.getItem("token");
      await query.delete("/test/" + testId, {
        headers: { Authorization: token },
      });
      dispatch({ type: "delete_test", payload: testId });
      Alert.alert("", "试卷删除成功", [
        {
          text: "确定",
        },
      ]);
    } catch (err) {
      console.log("删除试卷失败", err);
      Alert.alert("", "删除试卷失败");
    }
    setIsTestLoading(false);
  };

  const setStatus = async (testId) => {
    let option = { _id: testId };

    try {
      setIsTestLoading(true);
      const token = await AsyncStorage.getItem("token");
      const result = await query.post("/test/publish", option, {
        headers: { Authorization: token },
      });
      dispatch({ type: "set_status", payload: result.data.data });
      Alert.alert("", "测试发布成功", [
        {
          text: "确定",
        },
      ]);
    } catch (err) {
      console.log("测试发布失败", err);
      Alert.alert("", "测试发布失败");
    }
    setIsTestLoading(false);
  };

  return (
    <TestContext.Provider
      value={{
        testLists: testLists,
        addTest,
        editTest,
        deleteTest,
        setStatus,
        isTestLoading,
      }}
    >
      {children}
    </TestContext.Provider>
  );
};

export default TestContext;
